<template>
  <el-form
    :model="form"
    ref="form"
    :rules="rules"
    class="form"
  >
    <el-form-item
      class="form-item"
      prop="username"
    >
      <el-input
        placeholder="用户名/手机"
        v-model="form.username"
      >
      </el-input>
    </el-form-item>

    <el-form-item
      class="form-item"
      prop="password"
    >
      <el-input
        placeholder="密码"
        type="password"
        v-model="form.password"
      >
      </el-input>
    </el-form-item>

    <p class="form-text">
      <nuxt-link to="#">忘记密码</nuxt-link>
    </p>

    <el-button
      class="submit"
      type="primary"
      @click="submitForm"
    >
      登录
    </el-button>
  </el-form>

</template>

<script>
export default {
  data() {
    return {
      // 表单数据
      form: {
        username: "13800138000",
        password: "123456",
      },
      // 表单规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 点击登录按钮
    submitForm() {
      // 调用饿了么 form表单内置的验证方法 来验证 每一个表单是否合法
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 验证通过

          const data = {
            username: this.form.username,
            password: this.form.password,
          };

          // 派发action
          this.$store.dispatch("user/loginIn", data).then((res) => {
            // res = 123
            // 恭喜用户 成功登录
            // console.log("成功登录");
            this.$message.success("登录成功");

            // 判断一下有没有来源页面
            const sourceURL = this.$store.state.page.sourceURL;
            if (sourceURL) {
              // 存在 跳回去
              // 清空 sourceURL
               this.$store.commit("page/clearSourceURL");
              this.$router.replace(sourceURL);
            } else {
              // 不存在 跳转首页
              this.$router.replace("/");
            }
          });
        } else {
          // 验证失败
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.form {
  padding: 25px;
}

.form-item {
  margin-bottom: 20px;
}

.form-text {
  font-size: 12px;
  color: #409eff;
  text-align: right;
  line-height: 1;
}

.submit {
  width: 100%;
  margin-top: 10px;
}
</style>